package com.cxyzy.colorpickerbar

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.annotation.IntRange
import androidx.core.content.ContextCompat
import androidx.core.view.children


/**
 * 条形颜色选择器
 */
class ColorPickerBar(
    context: Context,
    attrs: AttributeSet?
) : LinearLayout(context, attrs) {
    private val viewWidth = 100
    private val viewHeight = 100
    private val margin = 20
    private lateinit var radioGroup: RadioGroup
    private var colors = ArrayList<Int>()
    private var selectedColorIndex = -1
    var radioCircleColor = "#FFFFFF"
    var colorPickerClickListener: ColorPickerClickListener? = null

    /**
     * 设置可选颜色数量，采用色值字符串，如: #D71345或#d71345
     */
    fun init(vararg colorStr: String) {
        colors.clear()
        colorStr.forEach { colors.add(Color.parseColor(it)) }
        init()
    }

    /**
     * 设置可选颜色数量，采用颜色资源定义,如: R.color.color1
     */
    fun init(vararg colorResId: Int) {
        colors.clear()
        colorResId.forEach { colors.add(ContextCompat.getColor(context, it)) }
        init()
    }

    private fun init() {
        removeAllViews()
        radioGroup = addRadioGroup()
        for (i in colors.indices) {
            radioGroup.addView(getRadioButton(i))
        }
    }

    /**
     * 设置默认选中项
     */
    fun selectItem(@IntRange(from = 0) itemIndex: Int) {
        if (itemIndex < radioGroup.childCount && itemIndex >= 0) {
            val selectedItem = radioGroup.children.elementAt(itemIndex)
            radioGroup.check(selectedItem.id)
        }
    }

    fun selectItemByColor(color: Int) {
        for (i in 0 until colors.size) {
            if (colors[i] == color) {
                selectItem(i)
            }
        }
    }

    private fun addRadioGroup(): RadioGroup {
        val radioGroup = RadioGroup(context)
        radioGroup.orientation = HORIZONTAL
        addView(radioGroup)
        return radioGroup
    }

    private fun getRadioButton(colorIndex: Int): RadioButton {
        val colorInt = colors[colorIndex]
        val radioButton = RadioButton(context)
        val layoutParams = LayoutParams(viewWidth, viewHeight)
        layoutParams.setMargins(margin, margin, margin, margin)
        radioButton.background = getCircleBg(colorInt)
        radioButton.layoutParams = layoutParams
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            radioButton.buttonTintList = ColorStateList.valueOf(Color.parseColor(radioCircleColor))
        }
        radioButton.setOnClickListener { colorPickerClickListener?.onClick(colorInt) }
        radioButton.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectedColorIndex = colorIndex
            }
        }
        return radioButton
    }

    /**
     * 获取选中的颜色值(整型)
     */
    fun getSelectedColor(): Int? {
        return if (selectedColorIndex >= 0 && selectedColorIndex < colors.size) {
            colors[selectedColorIndex]
        } else
            null
    }

    /**
     * 获取圆型背景
     * @param colorInt 整型色值
     */
    private fun getCircleBg(colorInt: Int) = GradientDrawable().also {
        it.shape = GradientDrawable.OVAL
        it.setColor(colorInt)
    }


    interface ColorPickerClickListener {
        fun onClick(selectedColor: Int)
    }
}
